const jwt = require('jsonwebtoken');

const JWT_SECRET = '123223';

const auth = async (ctx, next) => {
    try {
        const token = ctx.header.authorization?.replace('Bearer ', '');
        
        if (!token) {
            ctx.status = 401;
            ctx.body = {
                code: 401,
                errMsg: '请提供认证令牌'
            };
            return;
        }

        const decoded = jwt.verify(token, JWT_SECRET);
        ctx.state.user = decoded;
        
        await next();
    } catch (error) {
        ctx.status = 401;
        ctx.body = {
            code: 401,
            errMsg: '认证失败'
        };
    }
};

module.exports = { auth, JWT_SECRET }; 